<?php

namespace app\api\model\wanlshop;

use app\admin\model\User;
use app\admin\model\UserIntroduce;
use app\api\model\wanlshop\WithdrawalCash as WithdrawalCashModel;
use app\api\service\wanlshop\Common;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Model;

class WithdrawalCash extends Model
{
    // 表名
    protected $name = 'withdrawal_cash';

    // 自动写入时间戳字段
//    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';

    // 提现类型 // 0 回购提现 1 活动提现
    public static $wType = [
        '1' => '商品旧物提现',
        '2' => '余额提现',
        '3' => '活动提现',
        '4' => '转介绍提现',
    ];

    public static $bank = [
        'alipay' => '支付宝',
        'ALIPAY' => '支付宝账户',
        'WECHAT' => '微信账户',
        'ICBC' => '工商银行',
        'ABC' => '农业银行',
        'PSBC' => '邮储银行',
        'CCB' => '建设银行',
        'CMB' => '招商银行',
        'BOC' => '中国银行',
        'COMM' => '交通银行',
        'SPDB' => '浦发银行',
        'GDB' => '广发银行',
        'CMBC' => '民生银行',
        'PAB' => '平安银行',
        'CEB' => '光大银行',
        'CIB' => '兴业银行',
        'CITIC' => '中信银行'
    ];

    /**
     *  提现商品
     */
    public function withdrawGoods()
    {
        return $this->hasMany('app\api\model\wanlshop\WithdrawalGoods', 'w_id', 'w_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     *  提现列表
     */
    public function getMyWithdrawalCashLists($uid, $page, $pageSize)
    {
        // 条件
        $where["user_id"] = $uid;
        // 总条数
        $count = $this->where($where)->count();
        // 数据
        $list = $this->field('id, user_id, FROM_UNIXTIME(act_available_time) as act_available_time, w_act_state, FROM_UNIXTIME(createtime) as createtime, amount_withdrawal')
            ->where($where)
            ->order("id desc")
            ->paginate($pageSize, $count, ['page' => $page])
            ->toArray();

        $list['all_price'] = array_sum(array_column($list["data"], "amount_withdrawal"));
        return $list;
    }

    /**
     *  转介绍提现记录
     */

    public function introductionCashRecordModel($uid, $page, $pageSize)
    {
        // 条件
        $where["user_id"] = $uid;
        $where["w_type"] = 2;
        //总数量
        $count = $this->where($where)->count();
        // 数据
        $list = $this->field('id, user_id, FROM_UNIXTIME(createtime) as createtime, amount_withdrawal')
            ->where($where)
            ->order("id desc")
            ->paginate($pageSize, $count, ['page' => $page])
            ->toArray();
        return $list;
    }

    /**
     * 提现保存
     * @param $uid
     * @param $params
     * @return bool
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function handle($uid, $params)
    {
        //type --  1：商品旧物提现，2：余额提现，3：活动提现 4 转介绍
        $goods_ids = $order_ids = $original_order_ids = '';
        $balance = NULL;
        if ($params['type'] == 1) {
            if (!isset($params['goods_ids'])) {
                return '缺少参数goods_ids';
            }
            $goods_ids = explode(',', str_replace('，', ',', $params['goods_ids']));
            if (!$goods_ids) {
                return 'goods_ids参数错误';
            }
            $ids = explode(',', str_replace('，', ',', $params['ids']));
            if (!$ids) {
                return 'ids参数错误';
            }
            $order_ids = explode(',', str_replace('，', ',', $params['order_ids']));
            if (empty($order_ids)) {
                return 'order_ids参数错误';
            }
            $original_order_ids = explode(',', str_replace('，', ',', $params['original_order_ids']));
            if (empty($params['original_order_ids'])) {
                return 'original_order_ids参数错误';
            }
            //新增提现商品数据
            $goodsData = \db('wanlshop_goods')->where('id', 'in', $goods_ids)
                ->field(['id', 'title', 'image', 'price', 'platform', 'shop_id'])
                ->select();
            if ((count($goodsData) != count($goods_ids)) || (count($goodsData) != count($original_order_ids))) {
                return '商品参数数据错误';
            }
            $exist = WithdrawalGoods::where([
                'goods_id' => ['in', $goods_ids],
                'order_id' => ['in', $order_ids],
                'user_id' => $uid,
            ])->select();
            if ($exist) {
                return '商品不能重复提现';
            }
            $configGift = get_addon_config('wanlshop');
            $multiple = $configGift['gift']['mulriple'] ?? 2.2;
            $ava = array_sum(array_column($goodsData, 'price')) / $multiple;
            $ava = round($ava, 2);
            if ($params['amount'] != $ava) {
                return "当前商品可提现金额为 $ava 元";
            }
        }

        //公共参数验证
        switch ($params['channel']) {
            case 1:
                if (empty($params['truename']) || empty($params['mobile']) || empty($params['card_number'])) {
                    return '银行渠道参数错误';
                }
                if (self::cardNumberCheck($params['card_number']) === false) {
                    return '银行卡号校验失败';
                }
                if (empty($params['bank_type'])) {
                    return '银行类型参数错误';
                }
                if (empty($params['bank_name'])) {
                    return '银行名称参数错误';
                }
                $type = $params['bank_name'];
                break;
            case 2:
                if (empty($params['wechat_image'])) {
                    return '微信渠道参数错误';
                }
                $type = '微信';
                break;
            case 3:
                if (empty($params['alipay_account']) || empty($params['truename'])) {
                    return '支付号渠道参数错误';
                }
                $type = '支付宝';
                break;
        }

        //创建数据
        //1-商品旧物提现(换购)，2-余额提现 ，3-活动提现 4-转介绍
        $withDrawData = [
            'user_id' => $uid,
            'money' => $params['amount'],
            'type' => $type,
            'account' => !empty($params['alipay_account']) ? $params['alipay_account'] : (!empty($params["card_number"]) ? $params["card_number"] : (!empty($params["wechat_image"]) ? $params["wechat_image"] : "")),
            'memo' => '',
            'orderid' => $order_ids,
            'createtime' => time(),
            'updatetime' => time()
        ];

        $ins = array(
            'user_id' => $uid,
            'amount' => $params['amount'],
//            'shop_address' => $params['shop_address'],
            'type' => $params['type'],
            'tracking_number' => $params['tracking_number'] ?? '',
            'goods_ids' => $goods_ids ?? '',
            'image' => $params['image'] ?? '',
            'channel' => !empty($params['channel']) ? $params['channel'] : "",
            'truename' => !empty($params["truename"]) ? $params["truename"] : "",
            'alipay_account' => !empty($params['alipay_account']) ? $params['alipay_account'] : "",
            'wechat_image' => !empty($params["wechat_image"]) ? $params["wechat_image"] : "",
            'card_number' => !empty($params["card_number"]) ? $params["card_number"] : "",
            'mobile' => !empty($params["mobile"]) ? $params["mobile"] : "",
            'bank_name' => $params['bank_name'] ?? '',
            'bank_type' => $params['bank_type'] ?? '',
            'createtime' => time(),
        );

        Db::startTrans();
        try {
            $withdrawModel = new Withdraw();
            $w_id = $withdrawModel->insertGetId($withDrawData);
            (new WithdrawalCashModel())->insertGetId(array_merge($ins, ['w_id' => $w_id]));

            //1：商品旧物提现，2：余额提现，3：活动提现 4:转介绍提现
            switch ($params['type']) {
                case 1://商品旧物提现
                    WithdrawalCashModel::update([
                        'shop_address' => Shop::where('id', Goods::where('id', $goods_ids[0])->value('shop_id'))->value('return')
                    ], ['id' => $w_id]);

                    $goodsData = array_column((array)$goodsData, NULL, 'id');
                    $insData = [];
                    foreach ($goods_ids as $key => $item) {
                        $insData[] = [
                            'w_id' => $w_id,
                            'goods_id' => $item,
                            'order_id' => $order_ids[$key] ?? 0,
                            'user_id' => $uid,
                            'title' => $goodsData[$item]['title'] ?? '',
                            'image' => $goodsData[$item]['image'] ?? '',
                            'price' => $goodsData[$item]['price'] ?? 0,
                            'platform' => $goodsData[$item]['platform'] ?? 0,
                        ];
                    }

                    (new WithdrawalGoods())->insertAll($insData);

                    //更新为已提现
                    $orderGoodsModel = new OrderGoods();
                    $orderGoodsModel->where([
                        'goods_id' => ['in', $goods_ids],
                        'user_id' => $uid,
                        'order_id' => ['in', $order_ids],
                        'original_order_id' => ['in', $original_order_ids]
                    ])->update(['is_withdraw' => 1]);

                    break;
                case 2://余额提现
                    //支付宝转账最小0.1
                    if ($params['amount'] < 0.1) {
                        return '最小提现金额 0.1元';
                    }
                    $user = \app\common\model\User::find($uid);
                    if ($params['amount'] > $user->money) {
                        return '用户可提现余额不足';
                    }
                    $user->frozen = bcadd($user->frozen, $params['amount'], 2);
                    $user->money = bcsub($user->money, $params['amount'], 2);
                    $user->save();
                    break;
                case 3://活动提现，不在此处处理
                    break;
                case 4://转介绍提现
                    $balance = UserIntroduce::where('uid', $uid)->find();
                    if (!$balance || $params['amount'] > $balance['may_withdraw']) {
                        return '可提现金额不足';
                    }
                    //邀请表金额变更
                    $balance->withdrawing = bcadd($balance->withdrawing, $params['amount'], 2);//提现中
                    $balance->may_withdraw = bcsub($balance->may_withdraw, $params['amount'], 2);//可提现
                    $balance->save();
                    break;
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }

    /**
     * 提现列表
     * @param $params
     * @param $page
     * @param $size
     * @return array
     * @throws DbException
     */
    public function list($params, $size)
    {
        return (new self())
            ->with([
                'user' => function ($query) {
                    $query->withField('id,username,nickname,email,mobile,avatar,level,vip,gender,birthday,money,score');
                },
                'withdrawGoods'])
            ->where([
                'user_id' => $params['user_id'],
                'type' => $params['type']
            ])
            ->order('createtime', 'desc')
            ->paginate($size)
            ->each(function ($item) {
                $item->createtime = date('Y-m-d H:i:s', $item->createtime);
            })
            ->toArray();
    }

    /**
     * 银行卡号校验
     * @param $cardNo
     * @return bool
     */
    protected static function cardNumberCheck($cardNo)
    {
        $arr_no = str_split($cardNo);
        $last_n = $arr_no[count($arr_no) - 1];
        krsort($arr_no);
        $i = 1;
        $total = 0;
        foreach ($arr_no as $n) {
            if ($i % 2 == 0) {
                $ix = $n * 2;
                if ($ix >= 10) {
                    $nx = 1 + ($ix % 10);
                    $total += $nx;
                } else {
                    $total += $ix;
                }
            } else {
                $total += $n;
            }
            $i++;
        }
        $total -= $last_n;
        $total *= 9;
        return $last_n == ($total % 10);
    }
}
